import { Layout, Menu, message, Popconfirm } from "antd"
import {
    HomeOutlined,
    DiffOutlined,
    EditOutlined,
    LogoutOutlined
} from "@ant-design/icons"
import "./LayoutGeek.css"
import { Outlet, useLocation, useNavigate, useSearchParams } from "react-router-dom"
import { useDispatch, useSelector } from "react-redux"
import { useEffect } from "react"
import { fetchUserInfo, clearUserInfo } from "@/store/modules/user.js"

const { Header, Sider } = Layout


export default function LayoutGeek() {
    const [params] = useSearchParams()
    const items = [
        {
            label: "首页",
            key: "/",
            icon: <HomeOutlined />
        },
        {
            label: params.get("id") ? "编辑文章" : "创建文章",
            key: "/publish",
            icon: <EditOutlined />
        },
        {
            label: "文章管理",
            key: "/article",
            icon: <DiffOutlined />
        }
    ]

    const navigate = useNavigate()
    const location = useLocation()
    const onMenuClick = (path) => {
        // 防止在编辑文章中，点击侧边栏的编辑菜单时，文章id消失，但是回显数据还在的情况
        if(path.key === "/publish" && params.get("id")) return message.warning("正在编辑文章中 ！！！")
        navigate(path.key)
    }

    // 获取用户信息
    const dispatch = useDispatch()
    useEffect(() => {
        dispatch(fetchUserInfo())
    }, [dispatch])
    const userInfo = useSelector(state => state.user.userInfo)

    // 退出登录
    const onConfirm = () => {
        dispatch(clearUserInfo())
        navigate("/login")
    }
    return (
      <Layout>
          <Header className="header">
              <div className="logo" />
              <div className="user-info">
                  <span className="user-name">{userInfo.name}</span>
                  <span className="user-logout">
            <Popconfirm title="是否确认退出？" okText="退出" cancelText="取消" onConfirm={onConfirm}>
              <LogoutOutlined /> 退出
            </Popconfirm>
          </span>
              </div>
          </Header>
          <Layout>
              <Sider width={200} className="site-layout-background">
                  <Menu
                    mode="inline"
                    theme="dark"
                    selectedKeys={location.pathname}
                    items={items}
                    style={{ height: "100%", borderRight: 0 }}
                    onClick={onMenuClick}
                  />
              </Sider>
              <Layout className="layout-content" style={{ padding: 20 }}>
                  <Outlet />
              </Layout>
          </Layout>
      </Layout>
    )
}